﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace DIProject.Stock
{
    public partial class ShiftsOut : Form
    {
        private ToolStripMenuItem menuItem = null;

        public ShiftsOut()
            : this(null)
        {
        }

        public ShiftsOut(ToolStripMenuItem menuItem)
        {
            InitializeComponent();
            shiftOutUploadTableAdapter.ClearBeforeFill = true;
            this.menuItem = menuItem;
            if (menuItem != null)
                menuItem.Tag = this;
        }

        private void ShiftsOut_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (menuItem != null)
                menuItem.Tag = null;
        }
        //-------------------------------------------------------------------------------------------------
        private void ShiftsOut_Load(object sender, EventArgs e)
        {
            toolStripButtonUpdate.Enabled = false;
            toolStripButtonDelete.Enabled = false;
            toolStripRefresh_Click(toolStripButtonRefresh, EventArgs.Empty);
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private void toolStripRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                shiftsOutTableAdapter.Fill(stock.ShiftsOut);
            }
            catch (SqlException eq)
            {
                MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        //-------------------------------------------------------------------------------------------------
        private void toolStripInsert_Click(object sender, EventArgs e)
        {
            ShiftOut shiftOut = new ShiftOut(Util.ActionType.Insert, this);
            shiftOut.ShowDialog(this);
        }
        //-------------------------------------------------------------------------------------------------
        private void toolStripUpdate_Click(object sender, EventArgs e)
        {
            if (shiftsOutGridView.CurrentCell != null)
            {
                ShiftOut shiftOut = new ShiftOut(Util.ActionType.Update, this);
                shiftOut.ShowDialog(this);
            }
        }
        //-------------------------------------------------------------------------------------------------
        private void toolStripDelete_Click(object sender, EventArgs e)
        {
            int n;
            if ((n = shiftsOutGridView.SelectedRows.Count) > 0)
            {
                DIProject.DataSets.Stock.ShiftsOutRow[] rowsToDelete = new DIProject.DataSets.Stock.ShiftsOutRow[n];
                for (int i = 0; i < n; ++i)
                    rowsToDelete[i] = (DIProject.DataSets.Stock.ShiftsOutRow)((DataRowView)shiftsOutGridView.SelectedRows[i].DataBoundItem).Row;
                if (MessageBox.Show
                    (this
                    , string.Format
                        (n > 1
                        ? Properties.Resources.strDeleteShiftsOut
                        : Properties.Resources.strDeleteShiftOut
                        , n
                        , rowsToDelete[0].DocNumber
                        , rowsToDelete[0].DocDate
                        )
                    , Properties.Resources.strConfirmation
                    , MessageBoxButtons.YesNo
                    , MessageBoxIcon.Question
                    , MessageBoxDefaultButton.Button1
                    ) == DialogResult.Yes
                )
                {
                    try
                    {
                        for (int i = 0; i < n; ++i)
                            rowsToDelete[i].Delete();
                        shiftsOutTableAdapter.Update(stock.ShiftsOut);
                    }
                    catch (SqlException eq)
                    {
                        for (int i = 0; i < n; ++i)
                            rowsToDelete[i].RejectChanges();
                        MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (Exception ex)
                    {
                        for (int i = 0; i < n; ++i)
                            rowsToDelete[i].RejectChanges();
                        MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        //-------------------------------------------------------------------------------------------------
        private DIProject.DataSets.StockTableAdapters.ShiftOutLinesByIncomeTableAdapter shiftOutLinesByIncomeTableAdapter = new DIProject.DataSets.StockTableAdapters.ShiftOutLinesByIncomeTableAdapter();
        private DIProject.DataSets.StockTableAdapters.ShiftOutLinesTableAdapter shiftOutLinesTableAdapter = new DIProject.DataSets.StockTableAdapters.ShiftOutLinesTableAdapter();
        /// <summary>
        /// выгружаем документ из прихода
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonByIncome_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection selectedRows;
            ShiftOutByIncome shiftOutByIncome = new ShiftOutByIncome();
            if (shiftOutByIncome.ShowDialog(this) == DialogResult.OK
            && (selectedRows = shiftOutByIncome.gridView.SelectedRows).Count > 0)
            {
                DIProject.DataSets.Stock.ShiftOutLinesByIncomeRow incomeLineRow;
                DIProject.DataSets.Stock.ShiftOutByIncomeRow incomeRow;
                DIProject.DataSets.Stock.ShiftsOutRow shiftOutRow;
                DIProject.DataSets.Stock.ShiftOutLinesRow shiftOutLineRow;
                try
                {
                    decimal sum;
                    DateTime md = DateTime.Now;
                    string mw = FirstForm.Login;
                    int departmentId = (int)shiftOutByIncome.comboBoxDepartment.SelectedValue;
                    string departmentName = shiftOutByIncome.comboBoxDepartment.Text;
                    for (int i = selectedRows.Count - 1; i >= 0; --i)	// В обратном порядке
                    {
                        incomeRow = (DIProject.DataSets.Stock.ShiftOutByIncomeRow)((DataRowView)selectedRows[i].DataBoundItem).Row;
                        if (!incomeRow.IsRIDNull())
                            continue;
                        shiftOutRow = stock.ShiftsOut.NewShiftsOutRow();
                        shiftOutRow.ParentId = incomeRow.Id;
                        shiftOutRow.DepartmentId = departmentId;
                        shiftOutRow.DepartmentName = departmentName;
                        shiftOutRow.DocDate = DateTime.Today;
                        shiftOutRow.MD = md;
                        shiftOutRow.MW = mw;
                        shiftOutRow.DocNumber = incomeRow.DocNumber;
                        stock.ShiftsOut.AddShiftsOutRow(shiftOutRow);
                        shiftsOutTableAdapter.Update(shiftOutRow);
                        //shiftOutRow.
                        sum = 0m;
                        try
                        {
                            shiftOutLinesByIncomeTableAdapter.Fill(stock.ShiftOutLinesByIncome, incomeRow.Id);
                            for (int j = 0, m = stock.ShiftOutLinesByIncome.Count; j < m; ++j)
                            {
                                incomeLineRow = stock.ShiftOutLinesByIncome[j];
                                if (incomeLineRow.RestQntty < 1)
                                    continue;
                                shiftOutLineRow = stock.ShiftOutLines.NewShiftOutLinesRow();
                                shiftOutLineRow.DocId = shiftOutRow.Id;
                                shiftOutLineRow.PartyId = incomeLineRow.PartyId;
                                if (incomeLineRow.Qntty > incomeLineRow.RestQntty)	// Остаток партии меньше запрошенного количества
                                {
                                    shiftOutLineRow.Qntty = incomeLineRow.RestQntty;
                                    shiftOutLineRow.RetailSum = incomeLineRow.RestSum;
                                    shiftOutLineRow.Note = (incomeLineRow.RestQntty - incomeLineRow.Qntty).ToString();
                                }
                                else
                                {
                                    shiftOutLineRow.Qntty = incomeLineRow.Qntty;
                                    shiftOutLineRow.RetailSum = incomeLineRow.RetailSum;
                                }
                                shiftOutLineRow.MD = md;
                                shiftOutLineRow.MW = mw;
                                stock.ShiftOutLines.AddShiftOutLinesRow(shiftOutLineRow);
                                shiftOutLinesTableAdapter.Update(shiftOutLineRow);
                                sum += shiftOutLineRow.RetailSum;
                            }
                            shiftOutRow.Lines = stock.ShiftOutLinesByIncome.Count;
                            shiftOutRow.DocSum = sum;
                            shiftOutRow.AcceptChanges();
                        }
                        //если ошибка, удаляем весь документ и выводим сообщение об ошибке.
                        catch (Exception ee)
                        {
                            MessageBox.Show(ee.ToString());
                            DIProject.Data.ShiftOut.ShiftOutDelete(shiftOutRow.Id, shiftOutRow.MD);
                            //shiftOutRow.MD
                        }
                    }
                }
                catch (SqlException eq)
                {
                    MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        //-------------------------------------------------------------------------------------------------
        private DIProject.DataSets.StockTableAdapters.ShiftOutUploadTableAdapter shiftOutUploadTableAdapter = new DIProject.DataSets.StockTableAdapters.ShiftOutUploadTableAdapter();
        private DIProject.DataSets.StockTableAdapters.ShiftOutLinesUploadTableAdapter shiftOutLinesUploadTableAdapter = new DIProject.DataSets.StockTableAdapters.ShiftOutLinesUploadTableAdapter();
        private void toolStripButtonUpload_Click(object sender, EventArgs e)
        {
            int n, docId, departmentId;
            n = shiftsOutGridView.SelectedRows.Count;
            if (n < 1)
                return;
            DataGridViewRow row = shiftsOutGridView.SelectedRows[0];
            DataRowView drv = row.DataBoundItem as DataRowView;
            if (drv == null)
                return;
            DataSets.Stock.ShiftsOutRow rr = drv.Row as DataSets.Stock.ShiftsOutRow;
            Int32 dId = rr.Id;
            DataSets.StockTableAdapters.StockQueries adapt = new DIProject.DataSets.StockTableAdapters.StockQueries();
            object obj = adapt.ContragentDocNumberFromId(dId);
            string fName = "Файл выгрузки";
            if (!Convert.IsDBNull(obj) && obj != null)
            {
                fName = Convert.ToString(obj);
                fName = fName.Replace('/', '_');
                fName = fName.Replace('\\', '_');
            }
            saveFileDialog.FileName = fName;
            if (n > 0)
            {
                DIProject.DataSets.Stock.ShiftsOutRow[] rows = new DIProject.DataSets.Stock.ShiftsOutRow[n];
                for (int i = 0; i < n; ++i)
                    rows[i] = (DIProject.DataSets.Stock.ShiftsOutRow)((DataRowView)shiftsOutGridView.SelectedRows[i].DataBoundItem).Row;
                departmentId = rows[0].DepartmentId;
                for (int i = 1; i < n; ++i)
                    if (rows[i].DepartmentId != departmentId)
                    {
                        MessageBox.Show(this, Properties.Resources.strShiftOutUploadDepartmentError, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
                {
                    BinaryWriter binaryWriter = null;
                    try
                    {
                        if (File.Exists(saveFileDialog.FileName))
                            File.Delete(saveFileDialog.FileName);
                        binaryWriter = new BinaryWriter(File.OpenWrite(saveFileDialog.FileName));
                        binaryWriter.Write(departmentId);
                        binaryWriter.Write(n);
                        for (int i = n - 1; i >= 0; --i)	// В списке, почему-то, документы идут в обратном порядке...
                        {
                            docId = rows[i].Id;
                            shiftOutUploadTableAdapter.Fill(stock.ShiftOutUpload, docId);
                            shiftOutLinesUploadTableAdapter.Fill(stock.ShiftOutLinesUpload, docId);
                            DIProject.Util.DataTable.Save(null, stock.ShiftOutUpload, binaryWriter);
                            DIProject.Util.DataTable.Save(null, stock.ShiftOutLinesUpload, binaryWriter);
                        }
                    }
                    catch (SqlException eq)
                    {
                        MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        if (binaryWriter != null)
                            binaryWriter.Close();
                    }
                }
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (clickedCell != null)
            {
                updateToolStripMenuItem.Enabled = true;
                deleteToolStripMenuItem.Enabled = true;
            }
            else
            {
                updateToolStripMenuItem.Enabled = false;
                deleteToolStripMenuItem.Enabled = false;
            }
        }
        //-------------------------------------------------------------------------------------------------
        private DataGridViewCell clickedCell = null;
        private void shiftsOutGridView_MouseDown(object sender, MouseEventArgs e)
        {
            clickedCell = null;
            if (e.Button == MouseButtons.Right)
            {
                DataGridView.HitTestInfo hit = shiftsOutGridView.HitTest(e.X, e.Y);
                if (hit.Type == DataGridViewHitTestType.Cell)
                    shiftsOutGridView.CurrentCell = clickedCell = shiftsOutGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private void shiftsOutGridView_CurrentCellChanged(object sender, EventArgs e)
        {
            if (shiftsOutGridView.CurrentCell != null)
            {
                toolStripButtonUpdate.Enabled = true;
                toolStripButtonDelete.Enabled = true;
            }
            else
            {
                toolStripButtonUpdate.Enabled = false;
                toolStripButtonDelete.Enabled = false;
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private void shiftsOutGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                e.Handled = true;
        }
        //-------------------------------------------------------------------------------------------------
        private void shiftsOutGridView_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r' && shiftsOutGridView.CurrentCell != null)
                toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
        }
        //-------------------------------------------------------------------------------------------------
        private void shiftsOutGridView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo hit = shiftsOutGridView.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.Cell)
            {
                shiftsOutGridView.CurrentCell = clickedCell = shiftsOutGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
                toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
    }
}